package project.pianpian.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import project.pianpian.entity.User;
import project.pianpian.mapper.UserMapper;
import project.pianpian.utils.ReturnUtils;
import project.pianpian.utils.Token;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 * author :万霁初
 * date :2022/12/25 21:56
 **/
@RestController
@Slf4j
@RequestMapping("/main")
public class LoginPage {
    @Autowired
    UserMapper userMapper;

    @PostMapping("/login")
    public JSONObject login(@RequestBody JSONObject jsonObject){
        int id = jsonObject.getInteger("id");
        String password = jsonObject.getString("password");

        User user = userMapper.selectById(id);

        if (user==null){
            return ReturnUtils.fail(401,"账号不存在");
        }

        if (!password.equals(user.getPassword())){
            return ReturnUtils.fail(401,"密码错误");
        }

        String newToken= Token.create(id,password);
        user.setToken(newToken);
        userMapper.updateById(user);

        return ReturnUtils.success(201,"登陆成功",newToken);

    }

    @PostMapping("/register")
    public JSONObject register(@RequestBody JSONObject jsonObject){
        String name = jsonObject.getString("name");
        String password = jsonObject.getString("password");
        String phone = jsonObject.getString("phone");

        if (name.equals("")||name==null||name.length()>20){
            return ReturnUtils.fail(500,"名字不能为空，且长度不能超过20位");
        }

        Map map=new HashMap();
        map.put("name",name);
        List list = userMapper.selectByMap(map);
        if (list.size()!=0){
            return ReturnUtils.fail(400,"该用户名已被注册");
        }

        if (password.equals("")||password==null||password.length()<6){
            return ReturnUtils.fail(400,"密码长度不小于6位");
        }

        if (phone==null){
            return ReturnUtils.fail(400,"电话不能为空");
        }

        User user=new User(-1,name,password,"","",phone,0,"",new Date());
        int i = userMapper.insertUser(user);

        List<User> list1=userMapper.selectByMap(map);
        int id=list1.get(0).getId();

        return ReturnUtils.success(201,"注册成功",id);
    }
}
